// geolocation.ts

/**
 * 定义坐标类型
 */
interface Coordinates {
    latitude: number;
    longitude: number;
    accuracy: number;
    altitude?: number | null;
    altitudeAccuracy?: number | null;
    heading?: number | null;
    speed?: number | null;
}

/**
 * 获取当前地理位置
 * @param options 可选配置（高精度/超时时间等）
 * @returns Promise<Coordinates> 返回经纬度坐标
 * @throws 当获取失败时抛出错误
 */
export const getCurrentLocation = (
    options?: PositionOptions
): Promise<Coordinates> => {
    return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
            reject(new Error('您的浏览器不支持地理位置功能'));
            return;
        }

        navigator.geolocation.getCurrentPosition(
            (position: GeolocationPosition) => {
                resolve({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    accuracy: position.coords.accuracy,
                    altitude: position.coords.altitude,
                    altitudeAccuracy: position.coords.altitudeAccuracy,
                    heading: position.coords.heading,
                    speed: position.coords.speed
                });
            },
            (error: GeolocationPositionError) => {
                let errorMessage: string;
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        errorMessage = '用户拒绝了位置请求';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMessage = '无法获取位置信息';
                        break;
                    case error.TIMEOUT:
                        errorMessage = '请求位置超时';
                        break;
                    default:
                        errorMessage = '未知错误';
                }
                reject(new Error(errorMessage));
            },
            options
        );
    });
};